/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.message.service.welink.impl;

import com.huawei.welink.api.accesstoken.AuthV2TicketsRequest;
import com.huawei.welink.api.accesstoken.AuthV2TicketsResponse;
import com.huawei.welink.api.message.MessagesV2CardCommonRequest;
import com.huawei.welink.api.message.MessagesV2CardCommonResponse;
import com.huawei.welink.common.DefaultWeLinkClient;
import com.huawei.welink.common.exception.ApiException;
import com.je.common.base.util.StringUtil;
import com.je.message.Push;
import com.je.message.ResultMsgResp;
import com.je.message.exception.MessageSendException;
import com.je.message.service.AbstractThirdPartyPush;
import com.je.message.service.log.LogServiceFactory;
import com.je.message.service.welink.WeLinkMsgService;
import com.je.message.vo.MessageVo;
import com.je.meta.util.SettingHelper;
import com.je.meta.util.setting.Open.OpenWeLink;
import org.springframework.context.annotation.PropertySource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@PropertySource(value = "weLinkConfig.properties", encoding = "UTF-8")
public class WeLinkMsgServiceImpl extends AbstractThirdPartyPush implements WeLinkMsgService {

    @Value("${msgOwner}")
    private String msgOwner;

    @Value("${msgRange}")
    private String msgRange;

    final String WELINK_SENDCARDMSGURL = "https://open.welink.huaweicloud.com/api/messages/v2/card/common";
    final String RESULT_CODE = "0";
    final String WeLink_getTokenUrl = "https://open.welink.huaweicloud.com/api/auth/v2/tickets";

    public String initWeLinkService() {
        AuthV2TicketsResponse rsp = null;

            //从系统配置获取welink的id、secret
            OpenWeLink openWeLinkConfig = SettingHelper.getOpenWeLinkConfig();

            String clientId = openWeLinkConfig.getClientId();
            String clientSecret = openWeLinkConfig.getClientSecret();
            try {
                DefaultWeLinkClient client = new DefaultWeLinkClient(WeLink_getTokenUrl);
                AuthV2TicketsRequest req = new AuthV2TicketsRequest();
                req.setClientId(clientId);
                req.setClientSecret(clientSecret);
                rsp = client.execute(req);

            } catch (Exception e) {
                e.printStackTrace();
            }
        logger.info("获取到的token:" + rsp.getAccessToken());
        return rsp.getAccessToken();
    }

    @Override
    public ResultMsgResp send(MessageVo msgVo)  {
        //校验系统设置有没有勾选
        checkService(thirdPartyType.WELINK);
        //初始化服务 获取token
        String access_token = initWeLinkService();
        MessagesV2CardCommonResponse rsp = null;
        try {
            DefaultWeLinkClient client = new DefaultWeLinkClient(WELINK_SENDCARDMSGURL);
            MessagesV2CardCommonRequest req = new MessagesV2CardCommonRequest();
            req.setAccessToken(access_token);
            //从配置文件取 配置文件为空的话给默认值
            req.setMsgOwner(StringUtil.isEmpty(msgOwner) ? "JEPaaS" : msgOwner);
            req.setMsgRange(StringUtil.isEmpty(msgRange) ? "0" : msgRange);
            //获取人员信息
            List<String> userIds = getUserIds(msgVo, thirdPartyType.WELINK);

            req.setToUserList(userIds);
            req.setMsgTitle(msgVo.getMsgTitle());
            req.setMsgContent(msgVo.getMsgContent());
            req.setUrlPath(msgVo.getUrlPath());
            rsp = client.execute(req);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if (!RESULT_CODE.equals(rsp.getCode())) {
            msgVo.setErrorMessage(rsp.getMessage());
            LogServiceFactory.newLog(LogServiceFactory.LogTypeEnum.OTHER).saveAllLog(msgVo, Push.WELINK);
            return new ResultMsgResp(9999, rsp.getMessage(), false);
        }
        msgVo.setResult(rsp.getMessage());
        LogServiceFactory.newLog(LogServiceFactory.LogTypeEnum.OTHER).saveAllLog(msgVo, Push.WELINK);
        return new ResultMsgResp(200, "发送成功！", true);
    }


}
